package cn.com.flever.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.intellij.openapi.ui.Messages;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;

/**
 * 　* @Description: TODO
 * 　* @author qiyu
 * 　* @date 2021/1/23 1:20
 *
 */
public class ApiUploadUtils {

    //PDM上传地址
    private static String UPLOAD_URL = "http://***/7000/api/upload";


    /**
     * 上传PDM文件
     * @param file
     * @return
     */
    public static String upload(File file) {
        //填充参数
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
        //填充pdm文件对象
        //对pdm文件进行驼峰转换,并在当前目录生成
        byte[] bytesArray = new byte[(int) file.length()];
        try {
            FileInputStream fis = fis = new FileInputStream(file);
            fis.read(bytesArray); //read file into bytes[]
            fis.close();
            ByteArrayResource contentsAsResource = new ByteArrayResource(bytesArray) {
                @Override
                public String getFilename() {
                    return "file.pdm";
                }
            };
            paramMap.add("file", contentsAsResource);
            paramMap.add("token", "295abc96-74c3-4d46-8e22-8f367113fe05");
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("multipart/form-data");
            headers.setContentType(type);

            //用HttpEntity封装整个请求报文
            HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(paramMap, headers);

            //http调用
            JSONObject json = restTemplate.postForObject(UPLOAD_URL, files, JSONObject.class);
            //判断请求是否成功
            if (Boolean.TRUE.equals(json.get("succ"))) {
                Messages.showInfoMessage(
                        json.get("result").toString(),
                        "文档地址");
            }
            else{
                Messages.showErrorDialog(
                        json.get("message").toString(),
                        "上传MD文件出错");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
